package com.issoft.studentresitor.controller.student;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.issoft.studentresitor.domain.pojo.Clazz;
import com.issoft.studentresitor.domain.pojo.Result;
import com.issoft.studentresitor.domain.pojo.Student;
import com.issoft.studentresitor.domain.pojo.User;
import com.issoft.studentresitor.domain.vo.StudentVo;
import com.issoft.studentresitor.service.IClazzService;
import com.issoft.studentresitor.service.IStudentService;
import com.issoft.studentresitor.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "学生信息内容接口")
@RestController
@RequestMapping("/student/content")
public class StuContentController {
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IClazzService clazzService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据user_id查询个人信息
     */
    @ApiOperation("根据user_id查询个人信息")
    @GetMapping("/{userId}")
    public Result queryStuContent(@PathVariable Integer userId) {
        //构造redis的key
        String key = "stuContent:" + userId;
        //查询缓存
        Student student = (Student) redisTemplate.opsForValue().get(key);
        if (student != null ) {
            //缓存存在
            return Result.success(student);
        }
        // 使用 LambdaQueryWrapper 构建查询条件（类型安全）
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getUserId, userId); // 按 user_id 查询
        student = studentService.getOne(queryWrapper);
        redisTemplate.opsForValue().set(key, student);
        if (student == null) {
            return Result.error("未找到对应的学生信息");
        }
        StudentVo studentVo = new StudentVo();
        BeanUtil.copyProperties(student, studentVo);
        return Result.success(studentVo);
    }
    @ApiOperation("修改个人信息")
    @PostMapping("/updateInfo")
    public Result updateInfo(@RequestBody Student student){
        int i=studentService.updateInfo(student);
        if(i==0)
            return Result.error("修改失败");
        return Result.success(i);
    }
    @ApiOperation("根据user_id修改密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody User user){
        // 参数校验
        if (user.getUserId() == null) {
            return Result.error("用户ID不能为空");
        }

        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return Result.error("密码不能为空");
        }

        // 使用 Hutool 的 DigestUtil 进行加盐 MD5 加密
        // 可以使用用户ID或其他唯一标识作为盐值
        String encryptedPassword = DigestUtil.md5Hex(user.getPassword() );

        // 或者使用 BCrypt（更安全）
        // String encryptedPassword = cn.hutool.crypto.digest.BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());

        // 构建更新条件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, user.getUserId())
                .set(User::getPassword, encryptedPassword);

        // 执行更新操作
        boolean updated = userService.update(updateWrapper);

        if (updated) {
            return Result.success("密码修改成功");
        } else {
            return Result.error("密码修改失败，用户不存在");
        }
    }
    @ApiOperation("根据user_id查询班主任")
    @GetMapping("/queryTeacher/{userId}")
    public Result queryTeacher(@PathVariable Integer userId) {
        Clazz clazz = clazzService.getByIdQuerTeaacher(userId);
        return Result.success(clazz);
    }
    @ApiOperation("根据user_id查询班级同学")
    @GetMapping("/queryStudent/{userId}")
    public Result queryStudent(@PathVariable Integer userId) {
        List<Student> student= studentService.getByUIdQuerStudent(userId);
        return Result.success(student);
    }

    @ApiOperation("根据user_id查询同寝室的同学")
    @GetMapping("/queryDromStudent/{userId}")
    public Result queryDromStudent(@PathVariable Integer userId) {
        List<Student> student= studentService.queryDromStu(userId);
        return Result.success(student);
    }
    @ApiOperation("根据user_id修改修改学号、性别、联系电话、紧急联系人、紧急联系电话")
    @PostMapping("/updateStuInfo")
    public Result updateStuInfo(@RequestParam(value = "userId") Integer userId,
                                @RequestParam(value = "studentId") String studentId,
                                @RequestParam(value = "sex") Integer sex,
                                @RequestParam(value = "contactPhone") String contactPhone,
                                @RequestParam(value = "emergencyContact") String emergencyContact,
                                @RequestParam(value = "emergencyPhone") String emergencyPhone
                                ){
        return studentService.updateStuInfo(userId, studentId, sex, contactPhone, emergencyContact, emergencyPhone) ? Result.success() : Result.error("修改失败");
    }
    @ApiOperation("根据user_id修该联系人信息")
    @PutMapping("/updateContact")
    public Result updateContact(@RequestParam(value = "userId") Integer userId,
                                @RequestParam(value = "emergencyContact" , required = false) String emergencyContact,
                                @RequestParam(value = "emergencyPhone", required = false) String emergencyPhone,
                                @RequestParam(value = "contactPhone", required = false) String contactPhone){
        int i=studentService.updateContact(userId, emergencyContact, emergencyPhone, contactPhone);
        if(i==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }

}
